from views.base import BaseHandler
import json,re,time
from flask import make_response
from util.captcha.captcha import captcha
from util.redis import r
from util.comm import send_message
from util.db import db
from util.myjwt import myjwt
# 生成图片验证码
class Tu(BaseHandler):
    def get(self):
        name, text ,img = captcha.generate_captcha()
        uuid = self.get_query_argument('uuid')
        r.set_str(uuid,text)
        self.set_header('Content-Type','image/jpg')
        self.finish(img)

# 短信验证码
class Duan(BaseHandler):
    def get(self):
        data = json.loads(self.request.body)
        mobile = data['mobile']

        res = send_message.delay(mobile)
        print('res>>>>>>',res)
        self.finish({'code':200,'msg':'发送成功'})
# 图形验证码的判断
class Pan(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        uuid = data['uuid']
        mobile = data['mobile']
        tu = data['tu']
        code = r.get_str(uuid)
        ducode = r.get_str(mobile)
        if not all([mobile,tu,uuid]):
            self.finish({'code':400,'msg':"数据不能为空"})
        if not re.findall(r'1[3-9]\d{9}$',mobile):
            self.finish({'code':400,'msg':'手机号格式不正确'})
        if code:
            if tu.lower() != code.decode().lower():
                self.finish({'code':400,'msg':'图片验证码错误'})
            r.del_key(uuid)
        else:
            self.finish({'code':400,'msg':'没有获取到图片验证码'})
        # 一分钟发一次
        v = r.get_str(mobile)
        if v:
            self.finish({'code':400,'msg':'一分钟发送一次'})
        c = send_message(mobile)
        print(c)
        # 同一ip地址一分内只发送一次
        # s=self.request.remote_ip
        # if s:
        #     self.write({"code":406,"msg":"同一ip地址一分内只发送一次"})
        self.write({"code": 200, "msg": "ok"})

class Deng(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        mobile = data['mobile']
        duan = data['duan']
        code = r.get_str(mobile)
        if code:
            if str(code.decode()) != str(duan):
                self.finish({'code':400,'msg':'短信验证码错误'})
            r.del_key(mobile)
            sql = "select * from user where mobile='%s'"%mobile
            res = db.fetchone(sql)
            if res:
                data={'data':{'userid':res['id'],'mobile':res['mobile'],'ex':int(time.time())}}
                token = myjwt.jwt_en(data)
                self.finish({'code':200,'token':token,'userid':res['id'],'msg':'登录成功'})
            else:
                self.finish({'code':400,'msg':'用户不存在'})
        else:
            self.finish({'code':400,'msg':"验证码过期"})
